<template>
  <a-modal
    :open="open"
    title="选择数据源"
    width="800px"
    :footer="null"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <div class="data-source-modal">
      <!-- API搜索表单 -->
      <a-form :model="searchForm" layout="inline" style="margin-bottom: 16px;">
        <a-form-item label="接口搜索">
          <a-input-search
            v-model:value="searchForm.keyword"
            placeholder="请输入接口路径或描述"
            style="width: 300px;"
            @search="searchApis"
          />
        </a-form-item>
      </a-form>

      <a-row :gutter="16">
        <!-- API列表 -->
        <a-col :span="12">
          <div class="api-list-container" style="margin-bottom: 16px; max-height: 400px; overflow-y: auto;">
            <a-list
              :data-source="filteredApis"
              item-layout="horizontal"
              size="small"
            >
              <template #renderItem="{ item }">
                <a-list-item 
                  :class="{ active: selectedApi && selectedApi.path === item.path && selectedApi.method === item.method }"
                  @click="selectApi(item)"
                  style="cursor: pointer;"
                >
                  <a-list-item-meta>
                    <template #title>
                      <span>{{ item.path }}</span>
                    </template>
                    <template #description>
                      <span class="method" :class="item.method">{{ item.method.toUpperCase() }} - {{ item.summary }}</span>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </div>
        </a-col>
        
        <!-- 参数选择区域 -->
        <a-col :span="12">
          <div v-if="selectedApi" class="parameter-selection" style="max-height: 400px; overflow-y: auto;">
            <a-tabs v-model:activeKey="activeParamTab">
              <a-tab-pane key="input" tab="入参">
                <a-tree
                  v-if="inputParameters.length > 0"
                  :tree-data="inputParameters"
                  :checkable="true"
                  v-model:checkedKeys="checkedInputKeys"
                  :expanded-keys="expandedInputKeys"
                  @check="onInputCheck"
                  @expand="onInputExpand"
                  :field-names="{ children: 'children', title: 'name', key: 'key' }"
                >
                  <template #title="{ name, description }">
                    <a-tooltip v-if="description" :title="description">
                      <span>{{ name }}</span>
                    </a-tooltip>
                    <span v-else>{{ name }}</span>
                  </template>
                </a-tree>
                <a-empty v-else description="该接口无入参" />
              </a-tab-pane>
              <a-tab-pane key="output" tab="出参">
                <a-tree
                  v-if="outputParameters.length > 0"
                  :tree-data="outputParameters"
                  :checkable="true"
                  v-model:checkedKeys="checkedOutputKeys"
                  :expanded-keys="expandedOutputKeys"
                  @check="onOutputCheck"
                  @expand="onOutputExpand"
                  :field-names="{ children: 'children', title: 'name', key: 'key' }"
                >
                  <template #title="{ name, description }">
                    <a-tooltip v-if="description" :title="description">
                      <span>{{ name }}</span>
                    </a-tooltip>
                    <span v-else>{{ name }}</span>
                  </template>
                </a-tree>
                <a-empty v-else description="该接口无出参" />
              </a-tab-pane>
            </a-tabs>
          </div>
          
          <a-empty v-else description="请从左侧选择一个接口" />
        </a-col>
      </a-row>
      
      <!-- 按钮放在弹窗底部 -->
      <div style="text-align: right; margin-top: 16px;">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleOk" style="margin-left: 8px;">确定</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, reactive, inject, computed, watch } from 'vue'
import { SwaggerUtils } from '../swaggerUtils'

// 定义组件的属性
const props = defineProps({
  open: {
    type: Boolean,
    required: true
  }
})

// 定义组件的事件
const emit = defineEmits(['update:open', 'confirm'])

// 获取全局API状态
const apiState = inject('apiState')

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// API搜索结果
const filteredApis = computed(() => {
  if (!apiState.data) return []
  
  // 展平所有API
  const allApis = Object.entries(apiState.data.paths).flatMap(([path, methods]) => 
    Object.entries(methods).map(([method, details]) => ({
      path,
      method,
      summary: details.summary || ''
    }))
  )

  // 如果没有搜索关键字，返回所有API
  if (!searchForm.keyword) {
    return allApis
  }

  // 根据关键字过滤API（支持中文搜索）
  const term = searchForm.keyword.toLowerCase()
  return allApis.filter(api => 
    api.path.toLowerCase().includes(term) || 
    (api.summary && api.summary.toLowerCase().includes(term)) ||
    (api.path.includes(searchForm.keyword)) || 
    (api.summary && api.summary.includes(searchForm.keyword))
  )
})

// 选中的API
const selectedApi = ref(null)

// 活动参数Tab
const activeParamTab = ref('input')

// 入参和出参数据
const inputParameters = ref([])
const outputParameters = ref([])

// 选中的参数键
const checkedInputKeys = ref([])
const checkedOutputKeys = ref([])

// 展开的参数键
const expandedInputKeys = ref([])
const expandedOutputKeys = ref([])

// 处理嵌套属性，构建树形结构
function processNestedPropertiesAsTree(properties, prefix = '', level = 0, required = []) {
  if (!properties) return []
  
  let result = []
  Object.keys(properties).forEach(name => {
    const prop = properties[name]
    const fullName = prefix ? `${prefix}.${name}` : name
    
    // 创建当前节点（不预先定义 children）
    const currentNode = {
      key: fullName,
      name: name,
      type: prop.type || (prop.$ref ? 'object' : '未指定'),
      required: required.includes(name),
      description: prop.description || prop.title || '',
      level: level
    }
    
    // 收集子节点
    let children = []
    
    // 特殊处理requestBody参数
    if (name === 'requestBody') {
      if (prop.type === 'array' && prop.items) {
        // 处理数组类型的requestBody
        const items = prop.items;
        if (items.type === 'object' && items.properties) {
          children = processNestedPropertiesAsTree(
            items.properties, 
            fullName, 
            level + 1, 
            items.required || []
          )
        }
      } else if (prop.type === 'object' && prop.properties) {
        // 处理对象类型的requestBody
        children = processNestedPropertiesAsTree(
          prop.properties, 
          fullName, 
            level + 1, 
          prop.required || []
        )
      }
    }
    
    // 处理对象类型的嵌套属性
    if (prop.type === 'object' && prop.properties && name !== 'requestBody') {
      children = processNestedPropertiesAsTree(
        prop.properties, 
        fullName, 
        level + 1, 
        prop.required || []
      )
    }
    
    // 处理数组类型的嵌套属性（items 是对象）
    if (prop.type === 'array' && prop.items) {
      if (prop.items.type === 'object' && prop.items.properties) {
        children = processNestedPropertiesAsTree(
          prop.items.properties, 
          fullName, 
          level + 1, 
          prop.items.required || []
        )
      }
    }
    
    // 只有当存在子节点时才添加 children 属性
    if (children.length > 0) {
      currentNode.children = children
    }
    
    // 将当前节点加入结果
    result.push(currentNode)
  })
  
  return result
}

// 获取所有展开的输入参数行键值
const getAllExpandedKeys = (treeData) => {
  const keys = []
  const traverse = (nodes) => {
    nodes.forEach(node => {
      keys.push(node.key)
      if (node.children && node.children.length > 0) {
        traverse(node.children)
      }
    })
  }
  traverse(treeData)
  return keys
}

// 选中API
const selectApi = (api) => {
  selectedApi.value = api
  
  // 获取API详情
  const pathData = apiState.data.paths[api.path]
  const method = pathData[api.method]
  
  // 提取入参和出参
  const inputParams = SwaggerUtils.extractInputParams(method, apiState.data)
  const outputParams = SwaggerUtils.extractOutputParams(method, apiState.data)
  
  // 处理入参树形结构
  if (inputParams && inputParams.properties) {
    inputParameters.value = processNestedPropertiesAsTree(
      inputParams.properties,
      '',
      0,
      inputParams.required || []
    )
    expandedInputKeys.value = getAllExpandedKeys(inputParameters.value)
  } else {
    inputParameters.value = []
    expandedInputKeys.value = []
  }
  
  // 处理出参树形结构
  if (outputParams && outputParams.properties) {
    // 检查是否有data层级
    if (outputParams.properties.data) {
      const dataProp = outputParams.properties.data;
      
      // 处理所有属性，包括data和其他同级属性
      const allNodes = [];
      
      // 先处理data节点的同级节点（除了data本身）
      Object.keys(outputParams.properties).forEach(name => {
        if (name !== 'data') {
          const prop = outputParams.properties[name];
          const node = {
            key: name,
            name: name,
            type: prop.type || (prop.$ref ? 'object' : '未指定'),
            required: (outputParams.required || []).includes(name),
            description: prop.description || prop.title || '',
            level: 0
          };
          
          // 处理嵌套属性
          let children = [];
          if (prop.type === 'object' && prop.properties) {
            children = processNestedPropertiesAsTree(
              prop.properties,
              name,
              1,
              prop.required || []
            );
          } else if (prop.type === 'array' && prop.items && prop.items.properties) {
            children = processNestedPropertiesAsTree(
              prop.items.properties,
              name,
              1,
              prop.items.required || []
            );
          }
          
          if (children.length > 0) {
            node.children = children;
          }
          
          allNodes.push(node);
        }
      });
      
      // 然后专门处理data节点
      const dataNode = {
        key: 'data',
        name: 'data',
        type: dataProp.type || 'object',
        required: (outputParams.required || []).includes('data'),
        description: dataProp.description || dataProp.title || '数据主体',
        level: 0
      };
      
      // 处理data下的子属性
      let dataChildren = [];
      if (dataProp.type === 'array' && dataProp.items && dataProp.items.properties) {
        // 处理数组类型
        dataChildren = processNestedPropertiesAsTree(
          dataProp.items.properties,
          'data',
          1,
          dataProp.items.required || []
        );
      } else if (dataProp.properties) {
        // 处理对象类型
        dataChildren = processNestedPropertiesAsTree(
          dataProp.properties,
          'data',
          1,
          dataProp.required || []
        );
      }
      
      // 如果data有子节点，则添加children属性
      if (dataChildren.length > 0) {
        dataNode.children = dataChildren;
      }
      
      // 将data节点添加到所有节点中
      allNodes.push(dataNode);
      
      // 设置输出参数树，包含所有节点
      outputParameters.value = allNodes;
      expandedOutputKeys.value = getAllExpandedKeys(outputParameters.value);
    } else {
      // 默认处理方式（没有data层级）
      outputParameters.value = processNestedPropertiesAsTree(
        outputParams.properties,
        '',
        0,
        outputParams.required || []
      );
      expandedOutputKeys.value = getAllExpandedKeys(outputParameters.value);
    }
  } else {
    outputParameters.value = []
    expandedOutputKeys.value = []
  }
  
  checkedInputKeys.value = []
  checkedOutputKeys.value = []
}

// 入参勾选事件
const onInputCheck = (checkedKeys) => {
  checkedInputKeys.value = checkedKeys
}

// 出参勾选事件
const onOutputCheck = (checkedKeys) => {
  checkedOutputKeys.value = checkedKeys
}

// 入参展开事件
const onInputExpand = (expandedKeys) => {
  expandedInputKeys.value = expandedKeys
}

// 出参展开事件
const onOutputExpand = (expandedKeys) => {
  expandedOutputKeys.value = expandedKeys
}

// 获取选中字段的详细信息
const getSelectedFieldsInfo = (selectedKeys, treeData) => {
  const result = []
  
  // 递归查找节点
  const findNode = (nodes, key) => {
    for (const node of nodes) {
      if (node.key === key) {
        return node
      }
      if (node.children) {
        const found = findNode(node.children, key)
        if (found) {
          return found
        }
      }
    }
    return null
  }
  
  // 为每个选中的key查找详细信息
  for (const key of selectedKeys) {
    const node = findNode(treeData, key)
    if (node) {
      result.push({
        key: node.key,
        label: node.name,
        description: node.description || ''
      })
    }
  }
  
  return result
}

// 搜索API
const searchApis = () => {
  // 实际上已经在computed中处理了搜索逻辑
}

// 处理取消事件
const handleCancel = () => {
  emit('update:open', false)
}

// 处理确定事件
const handleOk = () => {
  if (!selectedApi.value) {
    return
  }
  
  // 获取选中的参数信息
  const selectedFields = activeParamTab.value === 'input' 
    ? getSelectedFieldsInfo(checkedInputKeys.value, inputParameters.value)
    : getSelectedFieldsInfo(checkedOutputKeys.value, outputParameters.value)
  
  const result = {
    path: selectedApi.value.path,
    method: selectedApi.value.method,
    paramType: activeParamTab.value === 'input' ? '入参' : '出参',
    selectedFields
  }
  
  emit('confirm', result)
  emit('update:open', false)
}

// 监听open属性变化，当弹窗关闭时重置状态
watch(() => props.open, (newVal) => {
  if (!newVal) {
    // 重置状态
    selectedApi.value = null
    searchForm.keyword = ''
    checkedInputKeys.value = []
    checkedOutputKeys.value = []
  }
})
</script>

<style scoped>
.method {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  margin-right: 8px;
}

.method.get {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.method.post {
  background-color: #ffa50014;
  color: #ff8c00;
  border: 1px solid #ffa500;
}

.method.put {
  background-color: #fffbe6;
  color: #faad14;
  border: 1px solid #ffe58f;
}

.method.delete {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.api-list-container .active {
  background-color: #e6f7ff;
}

.modal-footer {
  text-align: right;
}
</style>